package com.cmfi.controller.userRoleAuthController;

import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.cmfi.domain.userRoleAuthEntity.User;
import com.cmfi.domain.userRoleAuthEntity.UserRoleAndAuth;
import com.cmfi.service.inter.userRoleAuthInter.UserService;
import com.cmfi.utils.Code;
import com.cmfi.utils.Result;

@RestController
@RequestMapping("/api")
public class UserController {

    private final Logger log = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserService userService;

    @PostMapping("/register")//1、注册
	public Result createUser(@RequestBody JSONObject userJson) {
		try {
			User user = new User();
			if (userJson.containsKey("login")) {
				user.setUsername(userJson.getString("login"));
			}
			if (userJson.containsKey("password")) {
				user.setPassword(userJson.getString("password"));
			}
			boolean flag = userService.saveUser(user);
			return new Result(Code.SAVE_OK, flag);
		} catch (Exception e) {
			log.error("[UserController][createUser]  e,", e);
			return new Result(Code.SAVE_ERR, e.getMessage());
		}
	}
    
	@PutMapping("/admin/users")
	public Result updateUser(@RequestBody JSONObject userJson) {
		log.info("[UserController][updateUser] user:{}", userJson);
		try {
			User user = new User();
			if (userJson.containsKey("id")) {
				user.setId(userJson.getLong("id"));
			}
			if (userJson.containsKey("login")) {
				user.setUsername(userJson.getString("login"));
			}
			userService.updateUser(user);
			return new Result(Code.UPDATE_OK, user);
		} catch (Exception e) {
			log.error("[UserController][updatePassword]  e,", e);
			return new Result(Code.UPDATE_ERR, e.getMessage());
		}
	}

    @PutMapping("/user/password/{id}")//还是加一个id,userName也从前端传回来
    public Result updatePassword(@PathVariable(value = "id", required = false) final Long id,
			@RequestBody User user) {
		log.info("[UserController][updatePassword] user:{}", user);
		if (id == null) {
			return new Result(Code.UPDATE_ERR, "计划ID为空");
		}
		try {
			userService.updatePassword(id, user);
			return new Result(Code.UPDATE_OK, user);
		} catch (Exception e) {
			log.error("[UserController][updatePassword]  e,", e);
			return new Result(Code.UPDATE_ERR, e.getMessage());
		}
	}

	/**
	 * 获取所有用户
	 * 
	 * @param id 用户id
	 * @return Result
	 */
	@GetMapping("/admin/users")
	public Result getAllUsers(@RequestParam(required = false, defaultValue = "username") String sort,
			@RequestParam(required = false, defaultValue = "0") Integer page,
			@RequestParam(required = false, defaultValue = "0") Integer size) {
		try {
			List<User> users = userService.getAllUsers(sort, page, size);
			JSONArray userJson = convert(users);
			long total = userJson.size();
			return new Result(Code.SAVE_OK, userJson, total);
		} catch (Exception e) {
			log.error("[UserController][getAllUsers]  e,", e);
			return new Result(Code.SAVE_ERR, e.getMessage());
		}
	}

	@PutMapping("/user/authorize")
    public Result authorizeRoleForUser(@RequestParam Map<String, Object> params) {
        try {
        	Long userId = null;
        	Long roleId = null;
			if (params.containsKey("userId")) {
				userId = Long.parseLong(params.get("userId").toString());
			}
			if (params.containsKey("roleId")) {
				roleId = Long.parseLong(params.get("roleId").toString());
			}
        	userService.authorizeRoleForUser(userId, roleId);
    		return new Result(Code.UPDATE_OK, roleId.toString());
    	} catch (Exception e) {
    		log.error("[UserController][authorizeRoltForUser]  e,", e);
    		return new Result(Code.UPDATE_ERR, e.getMessage());
    	}
    }
    
	/**
	 * 根据用户id获取用户角色和权限
	 * 
	 * @param id 用户id
	 * @return Result
	 */
	@GetMapping("/user/{id}")
	public Result getUserRoleAndAuthorizeModules(@PathVariable(value = "id", required = false) final Long id) {
		try {
			List<UserRoleAndAuth> userAuths = userService.getUserRoleAndAuthorizeModules(id);
			long total = userAuths.size();
			return new Result(Code.SAVE_OK, userAuths, total);
		} catch (Exception e) {
			log.error("[UserController][getUserRoleAndAuthorizeModules]  e,", e);
			return new Result(Code.SAVE_ERR, e.getMessage());
		}
	}
	
	/**
	 * 根据用户id获取用户角色和权限
	 * 
	 * @param id 用户id
	 * @return Result
	 */
	@GetMapping("/account")
	public Result getUserAccount() {
		try {
			JSONObject userAccountList = userService.getUserAccount();
			long total = userAccountList.size();
			return new Result(Code.SAVE_OK, userAccountList, total);
		} catch (Exception e) {
			log.error("[UserController][getUserRoleAndAuthorizeModules]  e,", e);
			return new Result(Code.SAVE_ERR, e.getMessage());
		}
	}
	
	/**
	 * Description 转换形式
	 * 
	 * @param users List<User>
	 * @return JSONArray
	 */
	private JSONArray convert(List<User> users) {
		JSONArray array = new JSONArray();
		for (User user : users) {
			JSONObject obj = new JSONObject();
			obj.put("id", user.getId());
			obj.put("login", user.getUsername());
			obj.put("email", user.getEmail());
			obj.put("activated", true);
			obj.put("createdBy", user.getCreateBy());
			obj.put("createdDate", user.getCreateTime());
			obj.put("lastModifiedDate", user.getUpdateTime());
			obj.put("updateBy", user.getUpdateBy());
			array.add(obj);
		}
		return array;
	}


}
